<template>
  <div class="flex">
    <template v-if="processState === PROCESS_STATE.PENDING">
      <el-button v-if="hasRouteAuth('crm:finance:submitSealAmount')" class="submit-btn" type="primary" size="small" @click="handleSealSubmit">提交封账</el-button>
    </template>
    <template v-if="!showMobilePage">
      <div v-if="processState === PROCESS_STATE.PRELIMINARY_REVIEW" class="flex">
        <el-button v-if="hasRouteAuth('crm:finance:sellFirstTrial')" class="submit-btn" type="primary" size="small" @click="handelSubmit">提交复审</el-button>
        <el-button v-if="hasRouteAuth('crm:finance:sellFirstTrial')" class="cancel-btn" type="primary" size="small" @click="cancelJoin">取消参与封账</el-button>
      </div>
      <div v-if="processState === PROCESS_STATE.REVIEW" class="flex">
        <el-button v-if="hasRouteAuth('crm:finance:financeRecheck')" class="submit-btn" type="primary" size="small" @click="batchPass">批量通过</el-button>
        <el-button v-if="hasRouteAuth('crm:finance:financeRecheck')" class="cancel-btn" type="primary" size="small" @click="batchFail">批量拒绝</el-button>
        <el-button v-if="hasRouteAuth('crm:finance:financeRecheck')" class="cancel-btn" type="primary" size="small" @click="batchBackOut">批量作废</el-button>
      </div>
    </template>
    <template v-else>
      <MoreOperateBtn v-if="processState === PROCESS_STATE.PRELIMINARY_REVIEW">
        <el-dropdown-item v-if="hasRouteAuth('crm:finance:sellFirstTrial')" @click.native="handelSubmit">
          <div>提交复审</div>
        </el-dropdown-item>
        <el-dropdown-item v-if="hasRouteAuth('crm:finance:sellFirstTrial')" @click.native="cancelJoin">
          <div>取消参与封账</div>
        </el-dropdown-item>
      </MoreOperateBtn>
      <MoreOperateBtn v-if="processState === PROCESS_STATE.REVIEW">
        <el-dropdown-item v-if="hasRouteAuth('crm:finance:financeRecheck')" @click.native="batchPass">
          <div>批量通过</div>
        </el-dropdown-item>
        <el-dropdown-item v-if="hasRouteAuth('crm:finance:financeRecheck')" @click.native="batchFail">
          <div>批量拒绝</div>
        </el-dropdown-item>
        <el-dropdown-item v-if="hasRouteAuth('crm:finance:financeRecheck')" @click.native="batchBackOut">
          <div>批量作废</div>
        </el-dropdown-item>
      </MoreOperateBtn>
    </template>
    <SelectionNum :select-item="multipleSelectionAll" class="seal-select-num" @clearMixinSelection="clearMixinSelection" />
  </div>
</template>

<script>
import {
  cancelOrder, cancelPipeline,
  cancelVerification, isAudit,
  allReviewPass, allReviewFail,
  cancelCost, sealBillBackout,
  storeBatchSeal } from '@/api/sealingAccount';
import MoreOperateBtn from '@/components/Common/mobileComponents/moreOperate';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
// import { APPROVAL_STATUS } from '@/utils/const/cost';
import { PROCESS_STATE } from '@/utils/const/sealing';
import { mapState } from 'vuex';
export default {
  components: { MoreOperateBtn },
  props: {
    sealingId: {
      type: String | Number,
      default: ''
    },
    // 审核状态
    processState: {
      type: Number | String,
      default: PROCESS_STATE.REVIEW
    },
    columnType: { // 表格类型：order: 订单  pipeline: 流水列表 record: 核销记录
      type: String,
      default: 'order'
    },
    selectData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    multipleSelectionAll: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      PROCESS_STATE,
      remark: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    msgType() {
      switch (this.columnType) {
        case 'order':
          return '订单';
        case 'pipeline':
          return '流水';
        case 'record':
          return '核销记录';
        case 'cost':
          return '成本';
        default:
          return '订单';
      }
    },
    orderTypeStrToNum() {
      return {
        order: 0,
        pipeline: 1,
        record: 2,
        cost: 3
      };
    }
  },
  methods: {
    hasRouteAuth,
    clearMixinSelection() {
      this.$emit('clearMixinSelection');
    },
    // 提交复审
    handelSubmit() {
      const selectData = this.selectData;
      let msg = '';
      const isBatchAll = selectData.length <= 0;
      if (isBatchAll) {
        msg = `请确认是否提交全部${this.msgType}至财务复审`;
      } else {
        msg = `请确认是否提交${selectData.length}个${this.msgType}至财务复审`;
      }
      showModal(msg, '', {
        center: true,
        showClose: true
      }).then(() => {
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll });
        } else {
          // if (this.columnType === 'cost' && selectData.find(i => i.approvalStatus === APPROVAL_STATUS.REFUSE)) {
          //   showModal('所提交成本审批状态包含未过审<br />请调整后再提交', '', {
          //     center: true,
          //     showClose: true,
          //     dangerouslyUseHTMLString: true
          //   });
          // } else {
          this.submitReview(selectData);
          // }
        }
      });
    },
    // 提交复审
    submitReview(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id) : selectData;
      const params = this.getParams(ids);
      isAudit(params).then((res) => {
        if (res.code === 200) {
          this.refreshData();
          this.$message({ type: 'success', message: '提交复审成功' });
        } else {
          this.$message.error(res.message);
        }
      }).catch((res) => {
        this.listLoadingReset();
      });
    },
    // 批量通过
    batchPass() {
      const selectData = this.selectData;
      let msg = '';
      const isBatchAll = selectData.length <= 0;
      if (isBatchAll) {
        msg = `请确认是否通过全部${this.msgType}审批`;
      } else {
        msg = `请确认是否通过${selectData.length}个${this.msgType}审批`;
      }
      showModal(msg, '', {
        center: true,
        showClose: true
      }).then(() => {
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll, type: 'batchPass' });
        } else {
          this.batchPassRequest(selectData);
        }
      }).catch(() => {
        return;
      });
    },
    // 批量通过请求
    batchPassRequest(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id) : selectData;
      const params = this.getParams(ids);
      allReviewPass(params).then((res) => {
        if (res.code === 200) {
          this.refreshData();
          this.$message({ type: 'success', message: '通过成功' });
        } else {
          this.$message.error(res.message);
        }
      }).catch((res) => {
        this.listLoadingReset();
      });
    },
    // 批量撤销
    batchBackOut() {
      const { msgType } = this;
      const selectData = this.selectData;
      let msg = '';
      const isBatchAll = selectData.length <= 0;
      if (isBatchAll) {
        msg = msgType === '成本' ? '请确认是否作废审批<br />(当成本结算状态=已完成，成本退回待初审，审批状态不变)' : `请确认是否作废全部${msgType}审批`;
      } else {
        msg = msgType === '成本' ? `请确认是否作废${selectData.length}个审批<br />(当成本结算状态=已完成，成本退回待初审，审批状态不变)` : `请确认是否作废${selectData.length}个${msgType}审批`;
      }
      showModal(msg, '', {
        center: true,
        showClose: true,
        dangerouslyUseHTMLString: true
      }).then(() => {
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll, type: 'batchBackOut' });
        } else {
          this.batchBackOutRequest(selectData);
        }
      });
    },
    // 撤销审批请求
    batchBackOutRequest(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id) : selectData;
      const params = this.getParams(ids);
      sealBillBackout(params).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success', message: '作废成功' });
          this.refreshData();
        } else {
          this.$message.error(res.message);
        }
      }).catch((res) => {
        this.listLoadingReset();
      });
    },
    // 批量拒绝
    batchFail() {
      const selectData = this.selectData;
      let msg = '';
      const isBatchAll = selectData.length <= 0;
      if (isBatchAll) {
        msg = `请确认是否拒绝全部${this.msgType}审批`;
      } else {
        msg = `请确认是否拒绝${selectData.length}个${this.msgType}审批`;
      }
      this.$prompt(msg, '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel',
        center: true,
        type: 'warning',
        inputPlaceholder: '请输入审批未通过的原因',
        inputValidator: value => {
          if (value) {
            if (value.length > 50) {
              return '输入字符不得超过50个字';
            }
          } else {
            return '输入内容不得为空';
          }
        },
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            if (instance.inputValue.replace(/\s+/g, '')) {
              done();
            } else {
              this.$message({
                type: 'warning',
                message: '输入内容不能为空'
              });
            }
          } else {
            done();
          }
        }
      }).then(({ value }) => {
        this.remark = value;
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll, type: 'batchFail' });
        } else {
          this.batchFailRequest(selectData);
        }
      }).catch(() => {
        return;
      });
    },
    batchFailRequest(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id) : selectData;
      const params = this.getParams(ids);
      params.remark = this.remark.replace(/\s+/g, '');
      allReviewFail(params).then((res) => {
        if (res.code === 200) {
          this.refreshData();
          this.$message({ type: 'success', message: '拒绝成功' });
        } else {
          this.$message.error(res.message);
        }
      }).catch((res) => {
        this.listLoadingReset();
      });
    },
    // 取消封账Api
    cancelRequestApi() {
      const { columnType } = this;
      switch (columnType) {
        case 'order':
          return cancelOrder;
        case 'pipeline':
          return cancelPipeline;
        case 'record':
          return cancelVerification;
        case 'cost':
          return cancelCost;
        default:
          return cancelOrder;
      }
    },
    // 取消参与封账确认弹窗
    cancelJoin() {
      const { msgType } = this;
      const selectData = this.selectData;
      const isBatchAll = selectData.length <= 0;
      const message = !selectData || !selectData.length ? `请确认取消所有${msgType}参与封账` : `请确认取消所选${msgType}参与封账`;
      showModal(message, '', {
        center: true,
        showClose: true
      }).then(() => {
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll, type: 'cancelJoin' });
        } else {
          this.cancelJoinRequest(selectData);
        }
      });
    },
    // 提交封账
    handleSealSubmit() {
      const selectData = this.selectData;
      const isBatchAll = selectData.length <= 0;
      const message = !this.selectData || !this.selectData.length ? `请确认提交所有${this.msgType}参与封账` : `请确认提交所选${this.msgType}参与封账`;
      showModal(message, '', {
        center: true,
        showClose: true
      }).then(() => {
        if (isBatchAll) {
          // 批量操作事件未选择 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.$emit('queryClick', { isBatchAll, type: 'batchSeal' });
        } else {
          this.storeBatchSeal(this.selectData);
        }
      });
    },
    // 取消参与封账确认后请求不同类型对应的接口
    cancelJoinRequest(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id).join(',') : selectData.join(',');
      const params = {
        sealingId: this.sealingId,
        ids
      };
      const requestApi = this.cancelRequestApi();
      requestApi(params).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success', message: '取消成功' });
          this.refreshData();
        } else {
          this.$message.error(res.message);
        }
      }).catch((res) => {
        this.listLoadingReset();
      });
    },
    storeBatchSeal(selectData = []) {
      const ids = selectData[0].id ? selectData.map(i => i.id).join(',') : selectData.join(',');
      const type = this.orderTypeStrToNum[this.columnType];
      const params = {
        sealingId: this.sealingId,
        ids,
        type
      };
      storeBatchSeal(params).then(res => {
        if (res.code === 200) {
          this.$message.success('提交成功');
          this.refreshData();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listLoadingReset();
      });
    },
    // tool
    refreshData() {
      this.$emit('queryClick');
      this.$emit('refreshData');
      this.$emit('clearMixinSelection');
    },
    listLoadingReset() {
      this.$emit('queryClick', { listLoadingReset: true });
    },
    getParams(ids) {
      const params = {
        id: this.sealingId,
        type: 0 // 当前操作的是哪个表格： 0:订单  1:流水  2:核销记录
      };
      switch (this.columnType) {
        case 'order':
          params.orderIds = ids;
          params.type = 0;
          break;
        case 'pipeline':
          params.flowIds = ids;
          params.type = 1;
          break;
        case 'record':
          params.recordIds = ids;
          params.type = 2;
          break;
        case 'cost':
          params.costIds = ids;
          params.type = 3;
          break;
        default:
          params.orderIds = ids;
          break;
      }
      return params;
    }
  }
};
</script>

<style lang="scss" scoped>
.seal-select-num {
  margin-left: 10px;
}
.submit-btn {
  width: 96px;
  height: 32px;
  border: 1px solid #406EFF;
  opacity: 1;
  padding: 0;
  border-radius: 4px;
  background: #fff;
  color: #406EFF;
}
.cancel-btn {
  width: 96px;
  height: 32px;
  border: 1px solid #DDDDDD;
  border-radius: 4px;
  background: #fff;
  padding: 0;
  color: #666666;
  font-size: 14px;
}
.flex {
  display: flex;
}
</style>
